//
//  ThreeHomeViewController.swift
//  SwiftStudy
//
//  Created by chang on 2018/1/5.
//  Copyright © 2018年 chang. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class ThreeHomeViewController: UIViewController {

    var tableView : UITableView!
    var listArray = NSMutableArray.init()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.navigationItem.title = "小说阅读"
        
        self.initTableView()
        
        //这里以后可以扩展成搜索其他的书籍，先默认
        self.requestListData(keyword: "仙剑奇侠传4")
    }
    
    func requestListData(keyword: NSString) {
        let url = "http://app.jjwxc.net/iosapi/search"
        let parameDic = ["searchType":"1","sortMode":"DESC","type":"1","page":"1","keyword":keyword]
        self.view.makeToastActivity(.center)
        Alamofire.request(url, method: .post, parameters: parameDic).responseJSON {
            [weak self] (response) in
            self?.view.hideToastActivity()
            if let responseCC = response.result.value {
                let json = JSON(responseCC)
                self?.navigationItem.title = json["words"].string
                let items = json["items"].array
                self?.listArray.removeAllObjects()
                self?.listArray.addObjects(from: items!)
                self?.tableView.reloadData()
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension ThreeHomeViewController : UITableViewDataSource,UITableViewDelegate {
    
    func initTableView() {
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: self.navgationBarBottom, width: MAINSCREEN_WIDTH, height: MAINSCREEN_HEIGHT-self.navgationBarBottom-self.tabBarHeight));
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
    }
    
    //MARK: --UITableViewDataSource,UITableViewDelegate
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listArray.count
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let str = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: str)
        if cell == nil {
            cell = UITableViewCell.init(style: .default, reuseIdentifier: str)
            cell?.backgroundColor = UIColor.white
            cell?.selectionStyle = .none
            
            let lrVar = CGFloat(8) //距离左右屏幕的间隔
            let imageView = UIImageView.init(frame: CGRect.init(x: lrVar, y: 18, width: 80, height: 150-18*2))
            imageView.tag = 10
            imageView.backgroundColor = UIColor.defaultLineColor
            imageView.layer.borderColor = UIColor.defaultYellowColor.cgColor
            imageView.layer.borderWidth = 1;
            cell?.addSubview(imageView)
            
            let titleLabel = UILabel.init(frame: CGRect.init(x: imageView.right+5, y: imageView.top-4, width: tableView.width-imageView.right-5-12-96, height: 20))
            titleLabel.tag = 11
            titleLabel.textColor = UIColor.black
            titleLabel.font = UIFont.systemFont(ofSize: 15)
            cell?.addSubview(titleLabel)
            
            let textNumber = UILabel.init(frame: CGRect.init(x: tableView.width-12-96, y: titleLabel.top, width: 96, height: titleLabel.height))
            textNumber.tag = 12
            textNumber.textColor = UIColor.lightGray
            textNumber.font = UIFont.systemFont(ofSize: 11)
            textNumber.textAlignment = .right
            cell?.addSubview(textNumber)
            
            let authornameLabel = UILabel.init(frame: CGRect.init(x: titleLabel.left, y: titleLabel.bottom+5, width: titleLabel.width, height: titleLabel.height))
            authornameLabel.tag = 13
            authornameLabel.textColor = UIColorFromRGB(rgbValue: 0x556b2f)
            authornameLabel.font = UIFont.systemFont(ofSize: 14)
            cell?.addSubview(authornameLabel)
            
            let classLabel = UILabel.init(frame: CGRect.init(x: authornameLabel.left, y: authornameLabel.bottom+5, width: authornameLabel.width, height: authornameLabel.height))
            classLabel.tag = 14
            classLabel.textColor = UIColor.lightGray
            classLabel.font = UIFont.systemFont(ofSize: 13)
            cell?.addSubview(classLabel)
            
            let novelintroshortLabel = UILabel.init(frame: CGRect.init(x: classLabel.left, y: classLabel.bottom+5, width: classLabel.width, height: classLabel.height))
            novelintroshortLabel.tag = 15
            novelintroshortLabel.textColor = UIColor.lightGray
            novelintroshortLabel.font = UIFont.systemFont(ofSize: 13)
            cell?.addSubview(novelintroshortLabel)
            
            let tagsLabel = UILabel.init(frame: CGRect.init(x: novelintroshortLabel.left, y: novelintroshortLabel.bottom+5, width: novelintroshortLabel.width, height: novelintroshortLabel.height))
            tagsLabel.tag = 16
            tagsLabel.textColor = UIColorFromRGB(rgbValue: 0x556b2f)
            tagsLabel.font = UIFont.systemFont(ofSize: 13)
            cell?.addSubview(tagsLabel)
        }
        
        if let dic  = JSON(listArray.object(at: indexPath.row)).dictionary {
            let imageView = cell?.viewWithTag(10) as! UIImageView
            let cover = (JSON(dic)["cover"]).string
            imageView.sd_setImage(with: URL.init(string: cover!), completed: nil)
            
            let titleLabel = cell?.viewWithTag(11) as! UILabel
            let novelname = (JSON(dic)["novelname"]).string
            titleLabel.text = novelname
            
            let textNumber = cell?.viewWithTag(12) as! UILabel
            let novelsize = (JSON(dic)["novelsize"]).string
            let novelstep = (JSON(dic)["novelstep"]).string
            let nStep = (novelstep == "2") ? "(已完成)" : "(连载中)"
            textNumber.text = "\((novelsize ?? "0"))" + "字" + "\(nStep)"
            
            let authornameLabel = cell?.viewWithTag(13) as! UILabel
            let authorname = (JSON(dic)["authorname"]).string
            authornameLabel.text = authorname
            
            let classLabel = cell?.viewWithTag(14) as! UILabel
            let novelClass = (JSON(dic)["novelClass"]).string
            classLabel.text = novelClass
            
            let novelintroshortLabel = cell?.viewWithTag(15) as! UILabel
            let novelintroshort = (JSON(dic)["novelintroshort"]).string
            novelintroshortLabel.text = novelintroshort
            
            let tagsLabel = cell?.viewWithTag(16) as! UILabel
            let tags = (JSON(dic)["tags"]).string
            tagsLabel.text = tags
        }
        
        return cell!
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let dic  = JSON(listArray.object(at: indexPath.row)).dictionary {
            let novelid = (JSON(dic)["novelid"]).string
            let directoryVC = ReaderDirectoryViewController.init()
            directoryVC.novelidStr = novelid! as NSString
            directoryVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(directoryVC, animated: true)
        }
    }
}


